const FileHandle = require('./file-handle')
const inquirer = require('inquirer')

function buildContent(tablename, list) {
  let str = ''
  str = `const BaseModel = require('exmd') \
  \nconst fieldsMap = { \
  `
  list.forEach((item, key) => {
    str += `${key === 0 ? '\n' : '\n'}\t${item.field}: {\n`
    str += `\t\ttype: '${item.type}', \ 
    length: ${item.length}, \ 
    lengthvar: ${item.lengthvar}, \
    \n\t\tnotnull: ${item.notnull}, \ 
    comment: ${item.comment ? "'" + this.comment + "'" : null}${
      item.isPrimary ? ',' : ''
    } \
    ${item.isPrimary ? '\n\t\tisPrimary: ' + item.isPrimary : ''}${
      item.pk_name ? ',' : ''
    } \
    ${item.pk_name ? "\n\t\tpk_name: '" + item.pk_name + "'" : ''}
  }${key !== list.length - 1 ? ',' : ''}`
  })
  str += '\n}'
  str += `\n\nfunction ${tablename}() { \
  \n\tconst vm = this \
  \n\tBaseModel.apply(vm, arguments)\n`
  str += `\tvm.fields = fieldsMap\n\tvm.tableName = '${tablename}'\n`
  str += '}\n\n'
  str += `;(function() {\n\tconst TempFun = function(){} \
  \n\tTempFun.prototype = BaseModel.prototype \
  \n\t${tablename}.prototype = new TempFun() \
  \n})() \
  \n\nmodule.exports = ${tablename}
  `
  return str.trim()
}
/**
 * 生成model
 */
function buildModel(tableInfo) {
  const path = FileHandle.getModelPath()
  FileHandle.buildDirs(path).then(() => {
    const tablenameList = Object.keys(tableInfo)
    inquirer
      .prompt([
        {
          type: 'checkbox', // list列表 checkbox复选框
          name: 'type',
          message: '请选择要操作的表,按空格选择,按回车确定选择.',
          choices: [
            ...tablenameList.map((item) => {
              return {
                name: item
              }
            })
          ]
        }
      ])
      .then((res) => {
        const list = res.type
        for (let i = 0; i < list.length; i++) {
          let tablename = list[i]
          FileHandle.createFile(
            `${path}/${tablename}.js`,
            buildContent(tablename, tableInfo[tablename])
          ).then(() => {
            console.info('创建文件：', tablename)
          })
        }
      })
  })
}

exports.buildModel = buildModel
